/*
 * Copyright 2015-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.dcp.jeedcp.modules.report.service.datasource;

import com.dcp.jeedcp.common.persistence.Page;
import com.dcp.jeedcp.common.service.CrudService;
import com.dcp.jeedcp.modules.report.dao.datasource.DatasourceDao;
import com.dcp.jeedcp.modules.report.entity.datasource.Datasource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;

/**
 * 数据源设置Service
 * @author henry
 * @version 2017-05-12
 */
@Service
@Transactional(readOnly = true)
public class DatasourceService extends CrudService<DatasourceDao, Datasource> {

	public Datasource get(String id) {
		return super.get(id);
	}
	
	public List<Datasource> findList(Datasource datasource) {
		return super.findList(datasource);
	}
	
	public Page<Datasource> findPage(Page<Datasource> page, Datasource datasource) {
		return super.findPage(page, datasource);
	}
	
	@Transactional(readOnly = false)
	public void save(Datasource datasource) {
		super.save(datasource);
	}
	
	@Transactional(readOnly = false)
	public void delete(Datasource datasource) {
		super.delete(datasource);
	}

	/**
	 * @param driverClass
	 * @param url
	 * @param user
	 * @param password
	 * @return
	 */
	public boolean testConnection(String driverClass, String url, String user, String password) {
		Connection conn = null;
		try {
			Class.forName(driverClass);
			conn = DriverManager.getConnection(url, user, password);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		} finally {
			this.releaseConnection(conn);
		}
	}

	private void releaseConnection(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException ex) {
				ex.printStackTrace();
			}
		}
	}
	
	
}